import React, { lazy, useEffect, useState, useRef } from "react";
import './AI.css'
import 'animate.css';
import { ArrowLeft, PhoneCircleO, ClockO, AddO } from '@react-vant/icons';
import { startHeartbeat, resetTimeout } from '../../utils/heartbeatservice';
import { SyncLoader } from 'react-spinners'
import { chatInterface, addHistory } from "../../api/api";
import { useCustomNavigate } from '../../hooks/useNavigate';

const Deepseek = lazy(() => import('../../components/AI/Deepseek'))
const User = lazy(() => import('../../components/AI/User'))
const Historical = lazy(() => import('../../components/AI/Historical'))

const AI: React.FC = () => {
    const { goToPage, goBack, goForward } = useCustomNavigate()
    let [userMessage, setUserMessage] = useState({ role: 'user', content: '' })
    let [dialogueList, setDialogueList] = useState<{ role: string; content: string }[]>([])
    let [isLoading, setIsLoading] = useState(false)
    let [isHistory, setIsHistory] = useState(false)
    let [_id, set_id] = useState('')

    const [isListening, setIsListening] = useState(false);
    const recognitionRef = useRef<any>(null);

    useEffect(() => {
        setDialogueList([
            { role: 'assistant', content: '您好！我是小红，很高兴为您服务！' }
        ])
        startHeartbeat();
        return () => {
            resetTimeout();
        };
    }, []);

    useEffect(() => {
        if (dialogueList.length > 1) {
            saveHistory();
        }
    }, [dialogueList]);

    useEffect(() => {
        const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
        if (SpeechRecognition) {
            recognitionRef.current = new SpeechRecognition(); // 创建语音识别对象
            recognitionRef.current.continuous = true; // 是否连续识别
            recognitionRef.current.interimResults = true; // 是否显示中间结果
            recognitionRef.current.lang = 'zh-CN'; // 识别语言

            recognitionRef.current.onresult = (event: any) => {
                let interimTranscript = '';
                for (let i = event.resultIndex; i < event.results.length; i++) {
                    const transcript = event.results[i][0].transcript;
                    if (event.results[i].isFinal) {
                        setUserMessage(prev => ({ ...prev, content: prev.content + transcript }));
                    } else {
                        interimTranscript += transcript;
                    }
                }
                setUserMessage(prev => ({ ...prev, content: prev.content + interimTranscript }));
            };

            recognitionRef.current.onerror = (event: any) => {
                console.error('Speech recognition error', event);
                setIsListening(false);
            };
        }
    }, []);

    const toggleListening = () => {
        if (isListening) {
            recognitionRef.current?.stop();
        } else {
            recognitionRef.current?.start();
        }
        setIsListening(!isListening);
    };

    // 创建新的对话
    const createNewDialogue = () => {
        window.location.reload();
    };

    const handleKeyDown = async (e: any) => {
        if (e.key === 'Enter' && userMessage.content.trim() !== '') {
            const newDialogueList = [...dialogueList, userMessage];
            setDialogueList(newDialogueList);
            setUserMessage({ role: 'user', content: '' });
            setIsLoading(true)
            try {
                let response = await chatInterface(newDialogueList);
                const aiMessage = { role: 'assistant', content: response.data.choices[0].message.content };
                setDialogueList([...newDialogueList, aiMessage]);
            } catch (error) {
                console.error('Error sending message:', error);
                setDialogueList([...newDialogueList, { role: 'assistant', content: '服务器繁忙，请稍后再试。' }]);
            } finally {
                setIsLoading(false)
                scrollToBottom();
            }
        }
    }

    const scrollToBottom = () => {
        const chatContainer = document.querySelector('.chat-container');
        if (chatContainer) {
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }

    const saveHistory = async () => {
        const userId = localStorage.getItem('_id');
        try {
            const response = await addHistory({ _id: _id, userId: userId, content: dialogueList });
            set_id(response.data.id)
            console.log(response.data.msg)
        } catch (error) {
            console.log('历史记录保存:', error)
        }
    }

    const handleHistoryClick = (historyData: { role: string; content: string }[], id: string) => {
        setDialogueList(historyData);
        set_id(id);
        setIsHistory(false);
    };

    return (
        <div className="AI">
            {isHistory && (
                <div className="historical-container animate__animated animate__backInUp">
                    <div className={`historical-overlay ${isHistory ? 'show' : ''}`}></div>
                    <Historical closeHistory={() => setIsHistory(false)} onHistoryClick={handleHistoryClick} />
                </div>
            )}
            <div className="AI-top">
                <span className="AI-top-span" onClick={() => goBack()}><ArrowLeft fontSize={25} /></span>
                <span>客服-小红</span>
            </div>
            <div className="AI-middle">
                <div className="chat-container">
                    {dialogueList.map((dialogue, index) => (
                        dialogue.role === 'user' ? (
                            <User key={index} message={dialogue.content} />
                        ) : (
                            <Deepseek key={index} message={dialogue.content} />
                        )
                    ))}
                    {
                        isLoading && (
                            <Deepseek message={<SyncLoader color="#00BFFF" size={6} />} />
                        )
                    }
                </div>
            </div>
            <div className="AI-bottom">
                <PhoneCircleO fontSize={30} onClick={toggleListening} />
                <input
                    type="text"
                    placeholder={isListening ? "语音输入中..." : "输入新消息"}
                    value={userMessage.content}
                    onKeyDown={(e) => { handleKeyDown(e) }}
                    onChange={(e) => { setUserMessage({ ...userMessage, content: e.target.value }) }}
                />
                <ClockO fontSize={30} onClick={() => setIsHistory(true)} />
                <AddO fontSize={30} onClick={createNewDialogue} />
            </div>
        </div>
    )
}

export default AI